package com.biu.billiards.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.biu.billiards.model.bo.ShopBO;
import com.biu.billiards.model.entity.Shop;
import com.biu.billiards.mapper.ShopMapper;
import com.biu.billiards.model.vo.shop.AddShopVo;
import com.biu.billiards.model.vo.shop.GetShopVo;
import com.biu.billiards.model.vo.shop.UpdateShopVO;
import com.biu.billiards.model.vo.withdraw.AddWithdrawVo;
import com.biu.billiards.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.biu.billiards.utils.DT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.icbc.api.DefaultIcbcClient;
import com.icbc.api.IcbcConstants;
import com.icbc.api.request.MybankEnterprisePayPayentRequestV2;
import com.icbc.api.response.MybankEnterprisePayPayentResponseV2;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xue
 * @since 2023-09-25
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {



    @Resource
    private IWithdrawService withdrawService;

    @Resource
    private ShopMapper shopMapper;

    @Resource
    private IHardwareService hardwareService;


    @Resource
    private IUserService userService;
    @Resource
    private IBilliardsService billiardsService;


    @Resource
    private IDeviceService deviceService;


    @Override
    public Boolean autoWithdraw(AddWithdrawVo addWithdrawVo) {


        System.out.println("addWithdrawVo123123");
        System.out.println(addWithdrawVo);

        System.out.println((addWithdrawVo.getWithdrawPrice().multiply(new BigDecimal(100))).longValue());


         String APP_ID = "11000000000000017183";
         String APIGW_PUBLIC_KEY ="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCMpjaWjng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HXRLc9GkNXTpLBK+eSQ1QKBgQCQGO/Qjf0aQRahV5OwZfa7aC7SkciQLQIHmR3tPcUzqKUoqUxDx/4sPKTXNmh2DlmjyD2ZW+XRjpwqxnjEZoOD43JnRzPnke5cdAWfwDI9QQxLtgwjKZB3PSVZJ8f/+Pn7VM8S7B4M8AMU3YDFA/1lGSithrQ7tRJT65W/eaXiiwKBgD6T+u9kV6EYUG0SGbnOElLrNBq9Q+Z+cYLE/hI0Iqe+lDnaGkAyyNG5ZlYS/vNMFU4qHv0OFT8Z/V1F4AhyqS3DUk66PTwya7rl+si51+f4aJfyP1Xs0eOqenxG1b6+c+s6233FBMO/zAopdH5aRVgo6alUqHePffX+dCsluhBNAoGAT+/FeaiK8/mPmEmBAKZPzX7qGp4M6Q5OxfBHDcjqkNHJbVkdmaxkcB3kRA9Gu9cSGy2GHoFAaJP4RjJ75FgKNSwD1w9E1/24gUlLpWd1d02SiJ2g9hCkt8EP6vmKlZGE+8v8Y77gnMS4sOZ//MtN0ru2OS005rp4RF24YNQXFikCgYEAtMxwKnyfXSTaw8KPzVj42XCftNfdfSi5jV+CrcuC8kYChNN+yjWw8uutz/L8yIgiiL9zDxXafKfNBgOfId0UmPt85uAjpKcYHrpudlrDF2vmfXJgIOGs07He5WK8jsTAka32C0AntDotXJgwNk58UvQkwW8qTx5Z73Mi+0mFd/A=";


         String BASE_URL = "https://gw.open.icbc.com.cn/api";


        LocalDate currentDate = LocalDate.now();
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        // 将日期格式化为字符串
        String formattedDate = currentDate.format(formatter);


        // 获取当前日期和时间
        LocalDateTime currentDateTime = LocalDateTime.now();

        // 定义日期时间格式
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");

        // 将日期时间格式化为字符串
        String formattedDateTime = currentDateTime.format(formatter2);


        System.out.println("formattedTime212312");

        System.out.println(formattedDateTime);
        String URI = "mybank/enterprise/pay/payent/V2";


        List<MybankEnterprisePayPayentRequestV2.MybankEnterprisePayPayentRequestRdV2> rd = new ArrayList<>();

        MybankEnterprisePayPayentRequestV2.MybankEnterprisePayPayentRequestRdV2 rdV2 = new  MybankEnterprisePayPayentRequestV2.MybankEnterprisePayPayentRequestRdV2();



        rdV2.setPayType("2");
        rdV2.setIoFlag(addWithdrawVo.getBankType().toString());
        // rdV2.setPayeeAccount("6222021116006090123");
        rdV2.setPayeeAccount(addWithdrawVo.getBankCard());
        rdV2.setPayeeCnname(addWithdrawVo.getUserName());

        rdV2.setCurrency("CNY");

        rdV2.setAmount((addWithdrawVo.getWithdrawPrice().multiply(new BigDecimal(100))).longValue());
        rdV2.setiSeqNo(generateCabinetNum());
        rdV2.setPayerAccount("1103021009200566609");
        rdV2.setPayerCnname("梁溪剋壹杆台球休闲馆（个体工商户）");


        rd.add(rdV2);

        DefaultIcbcClient client = new DefaultIcbcClient(APP_ID, IcbcConstants.SIGN_TYPE_RSA2, PRI_KEY, IcbcConstants.CHARSET_UTF8, IcbcConstants.FORMAT_JSON,APIGW_PUBLIC_KEY, IcbcConstants.ENCRYPT_TYPE_AES,"", "", "");

        try {
            MybankEnterprisePayPayentRequestV2.MybankEnterprisePayPayentRequestBizV2 bizContent =
                    new MybankEnterprisePayPayentRequestV2.MybankEnterprisePayPayentRequestBizV2();
            MybankEnterprisePayPayentRequestV2 request = new MybankEnterprisePayPayentRequestV2();
            // 请对照接口文档用bizContent.setxxx()方法对业务上送数据进行赋值
            bizContent.setTransCode("PAYENT");
            bizContent.setTranDate(formattedDate);
            bizContent.setTranTime(formattedDateTime);
            bizContent.setLanguage("zh_CN");
            bizContent.setfSeqNo(generateCabinetNum());

            bizContent.setSettleMode("0");
            bizContent.setInstrCount(1);

            bizContent.setTotalAmount((addWithdrawVo.getWithdrawPrice().multiply(new BigDecimal(100))).longValue()    );


            bizContent.setRd(rd);



            request.setServiceUrl(BASE_URL + "/" + URI);
            request.setBizContent(bizContent);
            MybankEnterprisePayPayentResponseV2 response = client.execute(request);
            if (response.isSuccess()) {
                // 业务成功处理
                System.out.println("success");
                ObjectMapper objectMapper = new ObjectMapper();
                String json = objectMapper.writeValueAsString(response);
                System.out.println(json);

                if (userService.updateUserWith(Integer.parseInt(addWithdrawVo.getUserId()) ,addWithdrawVo.getUserType())){

                    addWithdrawVo.setWithdrawStatus(1);
                    addWithdrawVo.setWithdrawStartTime(LocalDateTime.now());
                    withdrawService.addWithdraw(addWithdrawVo);

                }


            } else {
                // 失败
                addWithdrawVo.setWithdrawStartTime(LocalDateTime.now());
                addWithdrawVo.setWithdrawStatus(2);
                withdrawService.addWithdraw(addWithdrawVo);

                System.out.println("error");
                ObjectMapper objectMapper = new ObjectMapper();
                String json = objectMapper.writeValueAsString(response);
                System.out.println(json);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    private  String generateCabinetNum(){
        String code = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");
        Random re = new Random();
        //生成一个随机四位数
        String random = String.valueOf(re.nextInt(9999-1000+1)+1000);
        String ordernumber = code+random;
        return "RF"+ordernumber;
    }


    @Override
    public Boolean getAutoOpenStatus(String deviceId) {

        Integer shopId = hardwareService.getShopId(deviceId);

//        QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("shop_id",shopId);
//        Shop shop = shopMapper.selectOne(queryWrapper);

        Boolean openBilliards = billiardsService.getBilliardsStatus(shopId);


//        List<Device> deviceList = deviceService.getDeviceList();
//        Boolean openDevice = false;


        return  openBilliards;


    }

    @Override
    public Boolean getAutoStatus(String deviceId) {


        System.out.println("deviceIddeviceIddeviceId");
        Integer shopId = hardwareService.getShopId(deviceId);

        QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shop_id",shopId);
        Shop shop = shopMapper.selectOne(queryWrapper);

        return shop.getAuto() == 1;


    }

    @Override
    public Shop getShop(Integer shopId) {
        QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shop_id",shopId);
        return shopMapper.selectOne(queryWrapper);


    }

    @Override
    public Boolean addWallet(Integer shopId, BigDecimal price) {
        QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shop_id",shopId);
        Shop shop = shopMapper.selectOne(queryWrapper);

        shop.setWallet(shop.getWallet().add(price));

        return shopMapper.update(shop, queryWrapper) == 1;
    }

    @Override
    public Boolean changeAutoStatus(GetShopVo getShopVo) {

        QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shop_id",getShopVo.getShopId());
        Shop shop = shopMapper.selectOne(queryWrapper);

        shop.setAuto(getShopVo.getAuto());

        return shopMapper.update(shop, queryWrapper) == 1;
    }

    @Override
    public List<ShopBO> getShopList(GetShopVo getShopVo) {

        List<ShopBO> list = new ArrayList<>();
        String[] str =  getShopVo.getShops().split(",");




         for (String shopId:str){

             GetShopVo newVo = new GetShopVo();

             newVo.setShopId(Integer.parseInt(shopId));

             ShopBO shopBO =  getShop(newVo);
             list.add(shopBO);
         }


        return list;
    }

    @Override
    public List<Shop> selectShopList() {
        QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("shop_id",getShopVo.getShopId());
         return shopMapper.selectList(queryWrapper);


    }

    @Override
    public ShopBO getShop(GetShopVo getShopVo) {

        QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shop_id",getShopVo.getShopId());
        Shop shop = shopMapper.selectOne(queryWrapper);

        ShopBO shopBO = new ShopBO();
        BeanUtils.copyProperties(shop,shopBO);
        return shopBO;
    }

    @Override
    public IPage<ShopBO> getShopPage(GetShopVo getShopVo) {


        QueryWrapper<Shop> query = new QueryWrapper<>();
        //新建分页条件
        Page<Shop> p = new Page<>(getShopVo.getCurrentPage(),getShopVo.getPageSize());
        IPage<Shop> userIPage = shopMapper.selectPage(p,query);
        IPage<ShopBO> page = new Page<>();
        List<ShopBO> adminDetailBOList = new ArrayList<>();

        for (Shop admin: userIPage.getRecords()){
            ShopBO adminDetailBO = new ShopBO();
            BeanUtils.copyProperties(admin,adminDetailBO);

            if (getShopVo.getLat()!=null && getShopVo.getLng()!=null){

                String[] str = admin.getCoordinate().split(",");

                int meter1 = (int) DT.getDistance(getShopVo.getLat(),getShopVo.getLng(),str[0],str[1]);
                adminDetailBO.setDistance(String.valueOf(meter1));

            }

            adminDetailBOList.add(adminDetailBO);
        }


        Collections.sort(adminDetailBOList, Comparator.comparingDouble(adminDetailBO -> {
            // 假设距离以 double 形式存储在 ShopBO 中
            System.out.println("sadxxxxcxc");
            return Double.parseDouble(adminDetailBO.getDistance());
        }));

//        Collections.sort(adminDetailBOList, Collections.reverseOrder(Comparator.comparingDouble(adminDetailBO ->
//                Double.parseDouble(adminDetailBO.getDistance()))));







        /* 将转化的BO放到的Records里面  */
        page.setRecords(adminDetailBOList);
        page.setCurrent(userIPage.getCurrent());
        page.setPages(userIPage.getPages());
        page.setPages(userIPage.getSize());
        page.setTotal(userIPage.getTotal());

        return page;
    }

    @Override
    public Boolean updateShop(UpdateShopVO updateShopVO) {
        QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shop_id",updateShopVO.getShopId());
        Shop shop = shopMapper.selectOne(queryWrapper);


        shop.setShopPhone(updateShopVO.getShopPhone());
        shop.setShopName(updateShopVO.getShopName());
        shop.setAddress(updateShopVO.getAddress());
        shop.setCoordinate(updateShopVO.getCoordinate());
        shop.setAuto(updateShopVO.getAuto());
        shop.setShopPics(updateShopVO.getShopPics());
        shop.setBanner(updateShopVO.getBanner());

        shop.setBankCardName(updateShopVO.getBankCardName());
        shop.setBankCard(updateShopVO.getBankCard());
        shop.setFeeType(updateShopVO.getFeeType());
        shop.setRecommendId(updateShopVO.getRecommendId());

        shop.setOpeningHours(updateShopVO.getOpeningHours());
        shop.setBankType(updateShopVO.getBankType());



    //    BeanUtils.copyProperties(updateShopVO,shop);


        return shopMapper.update(shop, queryWrapper) == 1;
    }

    @Override
    public Boolean addShop(AddShopVo addShopVo) {
        Shop shop = new Shop();
        BeanUtils.copyProperties(addShopVo,shop);
        return shopMapper.insert(shop) == 1;
    }

    @Override
    public Boolean deleteShop(Integer shopId) {
        QueryWrapper<Shop> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shop_id",shopId);
        return shopMapper.delete(queryWrapper) == 1;
    }
}
